<?php
/**
 * 评论管理
 */
namespace Admin\Controller;
use Admin\BaseController;
use Think\Model;
use Think\Page;
class CommentController extends BaseController
{

	/**
	 * 评论管理页
	 * Author: shijy
	 */
	public function index()
	{
		$objType 	= I('get.objType', 0, 'int');//被评论对象类型

		try {
			$commentM = M("comment_{$objType}", null, DB_MAIN_CFG);
		}catch (\Exception $e){
			$this->error("您所指定的类型暂时未开通评论功能");
			die;
		}


		$objID 		= I('get.objID', 0, 'int');//被评论对象编号
		//以上两个参数可以由资讯管理，活动管理等传参跳转过来

		$keywords = I('get.keyword');//关键字，优先级高于$objID


		$where = 'parentID=0';
		if ($objType > OBJ_TYPE_ALL) {
			if ($keywords) {
				switch ($objType) {
					case OBJ_TYPE_ACTIVITY:
						$activityM = M('a_activity', null, DB_MAIN_CFG);
						$ids = $activityM->where("activityName like '%{$keywords}%'")->getField('id', true);
						break;
					case OBJ_TYPE_ARTICLE:
						$activityM = M('article', null, DB_MAIN_CFG);
						$ids = $activityM->where("title like '%{$keywords}%'")->getField('id', true);
						break;
					case OBJ_TYPE_STORE:
						$activityM = M('s_store', null, DB_MAIN_CFG);
						$ids = $activityM->where("storeName like '%{$keywords}%'")->getField('id', true);
						break;
					default:
						$this->error("不存在的分类");
						break;
				}
				if (count($ids) > 0) {
					$objID = implode(',', $ids);
					$where .= " and objID in ({$objID}) ";
				}
			} elseif ($objID > 0) {
				$where .= " and objID={$objID} ";
			}
		} else {
			$objType = OBJ_TYPE_ALL;
			$keywords = '';
		}


		$nickName = I('get.nickname',null);
		if($nickName){
			$where .=" and nickname like '%{$nickName}%'";
		}


		$ofield = I('get.ofield');
		$otype = I('get.otype', '');

		if (strcmp($otype, '') == 0) {
			$field = null;
		} else {
			switch ($ofield) {
				case 1:
					$field = 'addtime';
					break;
				default:
					$field = null;
			}
		}


		if ($field) {
			$order = "{$field} {$otype}";
		} else {
			$order = null;
		}

		$count = $commentM->where($where)->count();

		$Page = new Page($count, 30);
		fetchPage($this->smarty, $Page);

		if ($order) {
			$list = $commentM->where($where)->order($order)->limit($Page->firstRow , $Page->listRows)->select();
		} else {
			$list = $commentM->where($where)->order("praiseNum DESC,addTime DESC")->limit($Page->firstRow , $Page->listRows)->select();
		}
		//die($list);


		//获取子评论，评论的评论
		$where=array();
		foreach($list as $v){
			$where[]=" (objType={$v['objType']} and parentID={$v['id']})";
		}
		$whereStr=implode(' or ',$where);
		$children=$commentM->where($whereStr)->order('objID desc,id desc')->select();

		foreach($children as $item){
			foreach($list as $k=>$v){
				if(!array_key_exists('children',$list[$k])){
					$list[$k]['children']=array();
				}
				if($item['objType']==$v['objType'] && $item['parentID']==$v['id']){
					$list[$k]['children'][]=$item;
				}
			}
		}


		$this->smarty->assign('ofield', $ofield);
		$this->smarty->assign('otype', $otype);

		$this->smarty->assign('topicType', C('OBJ_TYPE'));


		$this->smarty->assign('nickname', $nickName);
		$this->smarty->assign('objType', $objType);
		$this->smarty->assign('objID', $objID);
		$this->smarty->assign('keyword', $keywords);

		$this->smarty->assign('list', $list);
		$this->smarty->display('Comment/index.html');
	}

	/**
	 * 数据导出excel
	 * Author: shijy
	 */
	public function export(){
		$objType = I('get.objType', 0, 'int');//被评论对象类型
		$objID = I('get.objID', 0, 'int');//被评论对象编号
		//以上两个参数可以由资讯管理，活动管理等传参跳转过来

		$keywords = I('get.keyword');//关键字，优先级高于$objID

		$where = ' parentID=0 ';
		if ($objType > OBJ_TYPE_ALL) {
			if ($keywords) {
				switch ($objType) {
					case OBJ_TYPE_ACTIVITY:
						$activityM = M('a_activity', null, DB_MAIN_CFG);
						$ids = $activityM->where("activityName like '%{$keywords}%'")->getField('id', true);
						break;
					case OBJ_TYPE_ARTICLE:
						$activityM = M('article', null, DB_MAIN_CFG);
						$ids = $activityM->where("title like '%{$keywords}%'")->getField('id', true);
						break;
					default:
						$this->error("不存在的分类");
						break;
				}
				if (count($ids) > 0) {
					$objID = implode(',', $ids);
					$where .= " and objID in ({$objID}) ";
				}
			} elseif ($objID > 0) {
				$where .= " and objID={$objID} ";
			}
		} else {
			$objType = OBJ_TYPE_ALL;
			$keywords = '';
		}
		
		$nickName = I('get.nickname',null);
		if($nickName){
			$where .=" and nickname like '%{$nickName}%'";
		}
		$commentM = M("comment_{$objType}", null, DB_MAIN_CFG);
		$list = $commentM->field('1 as floor,uid,nickname,content,from_unixtime(addTime)')->where($where)->order("id asc")->select();
		foreach($list as $k=>$v){
			$list[$k]['floor']=$k+1;
		}
		exportExcel($list, array('楼层','用户编号','用户名','评论内容','评论时间'),'评论');

	}

	//审核
	public function disable()
	{
		$id = I('get.id', 0, 'int');
		$objType = I('get.objType', 0, 'int');
		if ($id < 1 || $objType < OBJ_TYPE_ALL) {
			$this->error("请指定操作对象");
		}

		$commentM = M("comment_{$objType}", null, DB_MAIN_CFG);
		$commentM->execute("update comment_{$objType} set isDisabled=1-isDisabled where id={$id}");
		$this->success("修改成功");
	}


	//删除
	public function delete()
	{
		$id = I('get.id', 0, 'int');
		$objType = I('get.objType', 0, 'int');
		if ($id < 1 || $objType < OBJ_TYPE_ALL) {
			$this->error("请指定操作对象");
		}

		$commentM = M("comment_{$objType}", null, DB_MAIN_CFG);
		$num=$commentM->where("id={$id}")->delete();
		$num+=$commentM->where("parentID={$id}")->delete();

		if($num>=1){
			changeObjCommentNum($objType,$id,0-$num);
		}
		$this->success("删除成功");
	}



	//回复
	public function reply(){
		$objID=I('post.id',0,'int');
		$objType=I('post.type',0,'int');
		$parentID=I('post.parentID',0,'int');
		$content=I('post.content','');

		if($objID==0||$objType==0||$parentID==0){
			$this->error("参数错误");
		}
		if(strlen($content)<3){
			$this->error("回复长度过短");
		}

		$uinfo = array(
			'uid'=>0,
			'nickname'=>C("SELF_NAME")
		);
		$this->comment($objType,$objID,$parentID,$content,$uinfo);
		$this->success("回复成功");

	}


	 /**
	 * 评论通用函数
	 * Author: shijy
	 * @param $objType
	 * @param $objID
	 * @param $parentID
	 * @param $content
	 * @param $userinfo
	 * @return mixed
	 */
	 private function comment($objType,$objID,$parentID,$content,&$userinfo){
		//评论列表
		$commentM=M('comment_'.$objType,null,DB_MAIN_CFG);
		$newData=array(
			'parentID'=>$parentID,
			'objType'=>$objType ,
			'objID'=>$objID ,
			'content'=>$content ,
			'uid'=> $userinfo['uid'],
			'nickname'=>$userinfo['nickname'] ,
			'addTime'=>time()
		);

		$result = $commentM->add($newData);
		if($result===false){
			return false;
		}

		$table=C('OBJ_TABLE');
		$table=$table[$objType];
		M($table,null,DB_MAIN_CFG)->where("id={$objID}")->setInc('commentNum');
	}

	//点赞
	public function praise(){
		$id=I('post.id',0,'int');		//评论的id
		$objType=I('post.type',0,'int');
		$praise=I('post.praise',0,'int');
		if($id==0){
			$this->error("参数错误");
		}
		$commentM = M('comment_'.$objType,null,DB_MAIN_CFG);
		$praiseInfo = $commentM->where("id={$id}")->field("praiseNum,editorPraiseNum")->find();
		$praiseInfo['praiseNum'] += $praise;
		$praiseInfo['editorPraiseNum'] += $praise;
		$res = $commentM->where("id={$id}")->save($praiseInfo);
		if($res !== false){
			//点赞日志
			$adminID = session(C('USER_AUTH_KEY'));
			$uinfo = M('gm_sys_user',null,DB_GM_CFG)->where("id={$adminID}")->field("uid,nickname")->find();

			$commentObjType = OBJ_TYPE_COMMENT_ARTICLE;	//默认为 对文章的评论的点赞
			if($objType == OBJ_TYPE_ACTIVITY){
				$commentObjType = OBJ_TYPE_COMMENT_ACTIVITY;
			}

			M('praise_log',null,DB_MAIN_CFG)->add(array(
				'objID'		=> $id,
				'objType'	=> $commentObjType,
				'uid'		=> $uinfo['uid'],
				'nickname'	=> $uinfo['nickname'],
				'addTime'	=> time(),
				'praiseNum'	=> $praise
			));
			$this->ajaxReturn(array('status' => 0,'msg' =>"点赞成功"));
		} else{
			$this->ajaxReturn(array('status' => 1,'msg' =>"点赞失败"));
		}
	}

	//取消点赞
	public function cancelPraise(){
		$commentID = I('post.commentId',0,'int');
		$praiseNum = I('post.praiseNum',0,'int');
		$objType = I('post.objType',0,'int');
		$editorPraiseNum = I('post.editorPraiseNum',0,'int');
		if($commentID == 0){
			$this->ajaxReturn(array('status'=>1,'msg'=>"参数错误"));
		}

		$minusPraiseNum['praiseNum'] = $praiseNum-$editorPraiseNum;
		$minusPraiseNum['editorPraiseNum'] = 0;
		$res = M('comment_'.$objType,null,DB_MAIN_CFG)->where("id={$commentID}")->save($minusPraiseNum);
		if($res !== false){
			$commentObjType = OBJ_TYPE_COMMENT_ARTICLE;	//默认为 对文章的评论的点赞
			if($objType == OBJ_TYPE_ACTIVITY){
				$commentObjType = OBJ_TYPE_COMMENT_ACTIVITY;
			}
			M('praise_log',null,DB_MAIN_CFG)->where("objType= {$commentObjType} and objID={$commentID} and praiseNum > 1")->delete();
			$this->ajaxReturn(array('status'=>0,'msg'=>"取消成功"));
		} else{
			$this->ajaxReturn(array('status'=>1,'msg'=>"取消失败"));
		}

	}
}
